package com.hxd.otc.module.wallet.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.dialog.ForbiddenBankCardDialog;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.wallet.bean.BasePayBean;
import com.hxd.otc.module.wallet.bean.PayInfoBean;
import com.hxd.otc.module.wallet.bean.PayOrderResultBean;
import com.hxd.otc.module.wallet.contract.RemotePayContract;
import com.hxd.otc.module.wallet.presenter.RemotePayPresenter;
import com.hxd.otc.utils.GsonUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.WalletDialogTipsUtil;

import butterknife.BindView;

/**
 * 作  者 :  卫广玉
 * 时  间 :  2018/6/13 10:18
 * 描  述 :  ${远程支付}
 */
public class RemotePayActivity extends PermissionActivity<RemotePayPresenter> implements RemotePayContract.View {

    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.iv_cancel)
    ImageView ivCancel;
    @BindView(R.id.pay_nums)
    TextView tvPayNums;
    @BindView(R.id.tv_order_info)
    TextView tvOrderInfo;
    @BindView(R.id.tv_payee_name)
    TextView tvPayeeName;
    @BindView(R.id.tv_payee_address)
    TextView tvPayeeAddress;
    @BindView(R.id.btn_change)
    Button btnChange;
    @BindView(R.id.ll_pay)
    LinearLayout llPay;
    @BindView(R.id.et_trade_pw)
    EditText etTradePw;
    @BindView(R.id.ll_tpw)
    LinearLayout llTpw;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.iv_see_hide)
    ImageView ivSeeHide;
    @BindView(R.id.fl_see_hide)
    FrameLayout flSeeHide;
    @BindView(R.id.tv_coin_type)
    TextView tvCoinType;

    private boolean isShowPsw;

    ObjectAnimator animPay;
    ObjectAnimator animTpw;

    public static final String REMOTE_COME = "remote_come";

    public static final int LOGIN_REQUEST = 6666;

    public static final int PAY_SUCCESS_REQUEST = 8888;

    //登录成功返回
    public static final int LOGIN_SUCCESS = 4180;
    //没登录返回
    public static final int LOGIN_FAIL = 4181;


    /**
     * 支付成功resultCode
     */
    int PAY_RESULT_CODE_SUCCESS = 40001;
    /**
     * 支付失败resultCode
     */
    int PAY_RESULT_CODE_FAIL = 40002;
    /**
     * 支付取消resultCode
     */
    int PAY_RESULT_CODE_CANCEL = 40003;

    /**
     * 支付返回信息
     */
    String RESULT_RESULT_EXTRA_MSG = "msg";

    private Intent mPayResultIntent = new Intent();
    private ForbiddenBankCardDialog<String> mTipSetValidTypeDialog;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_wallet_remote_pay;
    }

    @Override
    protected RemotePayPresenter createPresenter() {
        return new RemotePayPresenter(this);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {

        Bundle bundle = getBundle();
        if (bundle == null) {
            showToast(getString(R.string.failed_to_obtain_payment_information));
            return;
        }

        BasePayBean basePayBean = GsonUtil.fromJson(bundle.getString("value"), BasePayBean.class);
        if (basePayBean == null) {
            showToast(getString(R.string.failed_to_obtain_payment_information));
            return;
        }

        updataPayResultData(getString(R.string.for_cancellation), PAY_RESULT_CODE_CANCEL);
        updateUI(basePayBean.getPayInfoBean());
        mPresenter.setBasePayBean(basePayBean);
        if (!UserHelper.isLogin()) {
            skipLoginActivity();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        etTradePw.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                /*return true不会响应键盘打开事件，但是有响应触摸事件
                也就是说在响应触摸按下和松开后，事件就被消费而不往下传递了
                return false时，在触摸被松开的时候响应打开键盘事件，
                如果触摸长时间被按下，触摸松开时也不会对其他时间进行相应
                例如，不会打开系统默认键盘。
                */
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (!UserHelper.isSetPayPassword()) {
                            WalletDialogTipsUtil.showTpwTipsDialog(RemotePayActivity.this);
                        }
                        break;
                }
                return false;
            }
        });
        flSeeHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowPsw = !isShowPsw;
                if (isShowPsw) {
                    ivSeeHide.setBackgroundResource(R.mipmap.wallet_according_icon);
                    etTradePw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    ivSeeHide.setBackgroundResource(R.mipmap.wallet_hidden_icon);
                    etTradePw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                if (!TextUtils.isEmpty(etTradePw.getText())) {
                    etTradePw.setSelection(etTradePw.getText().length());
                }
            }
        });
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserHelper.isSetExValidType()) {
                    mTipSetValidTypeDialog = new ForbiddenBankCardDialog<String>(RemotePayActivity.this)
                            .setMessage(getString(R.string.your_are_not_set_valid_type_mode_is_go_to_setting))
                            .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                                @Override
                                public void onConfirm(String data) {
                                    $startActivity(SecurityCenterActivity.class);
                                }
                            });
                    mTipSetValidTypeDialog.show();
                } else {
                    checkDataAndPay();
                }
//                animPay = ObjectAnimator.ofFloat(llPay, "translationX", 0, -llPay.getWidth());
//                animPay.setDuration(450);
//                animPay.start();
//                animPay.addListener(new Animator.AnimatorListener() {
//                    @Override
//                    public void onAnimationStart(Animator animation) {
//                    }
//
//                    @Override
//                    public void onAnimationEnd(Animator animation) {
//                        llPay.setVisibility(View.GONE);
//                        setViewDefault(llPay, new Animator.AnimatorListener() {
//                            @Override
//                            public void onAnimationStart(Animator animation) {
//                            }
//
//                            @Override
//                            public void onAnimationEnd(Animator animation) {
//                                llTpw.setVisibility(View.VISIBLE);
//                            }
//
//                            @Override
//                            public void onAnimationCancel(Animator animation) {
//                            }
//
//                            @Override
//                            public void onAnimationRepeat(Animator animation) {
//                            }
//                        });
//                    }
//
//                    @Override
//                    public void onAnimationCancel(Animator animation) {
//                    }
//
//                    @Override
//                    public void onAnimationRepeat(Animator animation) {
//                    }
//                });
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animTpw = ObjectAnimator.ofFloat(llTpw, "translationX", 0, llTpw.getWidth());
                animTpw.setDuration(450);
                animTpw.start();
                animTpw.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        llTpw.setVisibility(View.GONE);
                        setViewDefault(llTpw, new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {
                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                llPay.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {
                    }
                });
            }
        });
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkDataAndPay();
            }
        });
        //默认不显示密码
        isShowPsw = true;
        flSeeHide.performClick();
    }

    private void skipLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra(REMOTE_COME, true);
        startActivityForResult(intent, LOGIN_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case LOGIN_REQUEST:
                if (resultCode == LOGIN_FAIL) {
                    updataPayResultData(getString(R.string.remote_login_fail), PAY_RESULT_CODE_FAIL);
                    finish();
                }
                break;
            case PAY_SUCCESS_REQUEST:
                finish();
                break;
        }
    }

    private void setViewDefault(View v, Animator.AnimatorListener al) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(v, "translationX", v.getTranslationX(), 0);
        animator.setDuration(0);
        animator.start();
        animator.addListener(al);
    }

    private void checkDataAndPay() {
        String payPassword = etTradePw.getText().toString().trim();
        mPresenter.payOrder(payPassword);
    }


    //显示数据
    private void updateUI(PayInfoBean payInfoBean) {
        tvPayNums.setText(String.valueOf(payInfoBean.getAmountCoin()));
        tvCoinType.setText(payInfoBean.getCoinType().toUpperCase());
        tvOrderInfo.setText(String.format("%s%s", payInfoBean.getMerchantName(), payInfoBean.getOrderId()));
        tvPayeeName.setText(payInfoBean.getToUserName());
        tvPayeeAddress.setText(payInfoBean.getToAddress());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (animPay != null && animPay.isRunning()) {
            animPay.cancel();
        }
        if (animTpw != null && animTpw.isRunning()) {
            animTpw.cancel();
        }
        UIUtils.dismissDialog(mTipSetValidTypeDialog);
    }

    @Override
    public void onTokenMiss() {
        UserHelper.cleanUserData();
        skipLoginActivity();
    }

    @Override
    public void payOrderSuccess(PayOrderResultBean payOrderResultBean) {
//        0待支付、1支付处理中、2支付成功、3.支付失败
        switch (payOrderResultBean.getStatus()) {
            case "0":
                payOrderFail(getString(R.string.unpaid));
                break;
            case "1":
                payOrderFail(getString(R.string.payment_processing));
                break;
            case "2":
                updataPayResultData(getString(R.string.remote_pay_success), PAY_RESULT_CODE_SUCCESS);
                Intent intent = new Intent(RemotePayActivity.this, RemotePaySuccessActivity.class);
                startActivityForResult(intent, PAY_SUCCESS_REQUEST);
                break;
            case "3":
            default:
                payOrderFail(getString(R.string.payment_failure));
                break;
        }


    }

    @Override
    public void payOrderFail(String errMessage) {
        showToast(errMessage);
        updataPayResultData(TextUtils.isEmpty(errMessage) ? getString(R.string.payment_failure) : errMessage, PAY_RESULT_CODE_FAIL);
    }

    private void updataPayResultData(String msg, int payResultCodeSuccess) {
        mPayResultIntent.putExtra(RESULT_RESULT_EXTRA_MSG, msg);
        setResult(payResultCodeSuccess, mPayResultIntent);
    }
}
